<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Tree View</title>
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="../bootstrap/bootstrap-treeview/bootstrap-treeview.css"
	rel="stylesheet">
</head>
<body>
	<div class="container">
		<h1>Bootstrap Tree View</h1>
		<br>
		<div class="row">
			<div class="col-sm-8">
				<h2>技术关键词分类表</h2>
				<div id="treeview5" class=""></div>
			</div>
		</div>

		<br /> <br />
	</div>
	<script src="../js/packages/jquery.js"></script>
	<script src="./bootstrap/bootstrap-treeview/bootstrap-treeview.js"></script>
	<script type="text/javascript">
    flowid=1;

    $('#insertSiblingButton').click(function(){
  		if($('#newKeyValue').val()==''){
  			alert('空不行')
  			return;
  		}
		//get selected node
        var nodeData = $('#treeview5').treeview('getSelected')[0];
		//console.log('selected')
        //console.log(nodeData)
  		$.ajax({
				url:'/fk/savesibkw',
			    type:'GET', //GET
			    async:false,    //或false,是否异步
			    data:{
			    	flowid : flowid,
			    	keywordValue : $('#newKeyValue').val(),
			    	parentid : nodeData.item_parent,
			    },
			    //timeout:5000,    //超时时间
			    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text

			    success:function(data,textStatus,jqXHR){
			        //console.log(data)
			        //successfully insert to database
			  	    var newData =  {
			    	        text: $('#newKeyValue').val(),
			    	        href: '#demo',
			    	        nodes:[],
			  	  	        item_id:data.id,
			  	            item_parent:data.parentId,
			    	        //tags: ['11']
			    	      };
			          $('#treeview5').treeview("addSiblingNode", [nodeData.nodeId,  newData]);			          
			    },
			    error:function(xhr,textStatus){
			        //console.log(xhr.responseText)
			        //console.log(textStatus)
			    },
			    complete:function(){console.log('结束')}
			});

  		/*
  		console.log('active '+activenode)
		if(activenode!='')
  	    	$('#treeview5').treeview("addNode", [activenode, {node: newData}]);
  		*/
  	});


//   	document.addEventListener("click", function(e){
// 		console.log(e.target)
// 		console.log(e.srcElement)
//   	})

      defaultData= [];
function formatData(data){
	defaultData = [];
	var keys = [];
	var stack = [];
	var treeviewData = [];
	//console.log(data.length)
	var rootNode = [];
	var leftNode = [];

	for(var o in data){
		//console.log(data[o].keywordValue + "  " + data[o].parentId)
		if(data[o].parentId == 0 ) {
			var item = {
					text:data[o].keywordValue,
					href:'#item_'+data[o].id,
		            tags: '0',
		            nodes:[],
		            item_id:data[o].id,
		            item_parent:0,
		            //levelll:0,
		            //order:0,
				}
			rootNode.push(item);
			//data.splice(o,1);
		}else{
			leftNode.push(data[o])
		}
	}
	data = leftNode;
	
// 	for(var o in data){
// 		console.log(data[o].keywordValue + "  " + data[o].parentId)
// 	}
	//console.log(data.length)
	for(var root_index in rootNode){
		stack = [];
		stack.push(rootNode[root_index])
		while(stack.length>0){
			//console.log(stack.length)
			var curr = stack[stack.length-1];
			var order = 0;
			var find_flag = false;
			for(var o in data){
				if(data[o].parentId == curr.item_id){
					var item = {
							text:data[o].keywordValue,
							href:'#item_'+data[o].id,
				            tags: '0',
				            nodes:[],
				            item_id:data[o].id,
				            item_parent:data[o].parentId,
				            //level:curr.level+1,
				            //order:0,
						}
					//console.log(item)
					//curr.nodes.push(item);
					order = order + 1
					stack.push(item);
					data.splice(o,1);
					//console.log(data.length)
					find_flag = true;
					break;
				}
			}
			
			if(find_flag) continue;
			
			if(stack.length>1) {
				stack[stack.length-2].nodes.push(curr);
				stack.splice(stack.length-1,1);
			}else{
				//console.log(stack[stack.length-1])
				defaultData.push(stack[0]);
				stack = []
				//break;
			}

			//console.log(stack[0]);
		}
	}
	//alert('yes')
	
}
  		$(function() {
  			
  			$.ajax({
  				url:'/sptree/readflow',
  			    type:'GET', //GET
  			    async:false,    //或false,是否异步
  			    data:{
  			    	flowid:flowid,
  			    	//pageNumber:pageNumber,
  			    	//perSize:perSize
  			    },
  			    //timeout:5000,    //超时时间
  			    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
  			    /*beforeSend:function(xhr){
  			        console.log(xhr)
  			        console.log('发送前')
  			    }*/
  			    success:function(data,textStatus,jqXHR){
  			    	formatData(data)
  			        //console.log(data)
  			        //console.log(textStatus)
  			        //console.log(jqXHR)
  			    },
  			    error:function(xhr,textStatus){
  			        console.log('什么错误')
  			        console.log(xhr.responseText)
  			        console.log(textStatus)
  			    },
  			    complete:function(){
  			        console.log('结束')
  			    }
  			});
      /*
        $('#treeview5').treeview({
          color: "#428bca",
          expandIcon: 'glyphicon glyphicon-chevron-right',
          collapseIcon: 'glyphicon glyphicon-chevron-down',
          nodeIcon: 'glyphicon glyphicon-bookmark',
          data: defaultData
        });
        */

        var initSelectableTree = function() {
            return $('#treeview5').treeview({
                color: "#428bca",
                expandIcon: 'glyphicon glyphicon-chevron-right',
                collapseIcon: 'glyphicon glyphicon-chevron-down',
                nodeIcon: 'glyphicon glyphicon-bookmark',
              data: defaultData,
              //multiSelect: $('#chk-select-multi').is(':checked'),
            	  /*
              onNodeSelected: function(event, node) {
                console.log(node.nodeId+' '+node.text + ' was selected');
                //newData.
                activenode = node.nodeId;
                var nodeData = $('#treeview5').treeview('getSelected')[0];
                //console.log(event.srcElement)
                //console.log(event.target)
                 $('#currKeyValue').val(nodeData.text);
              },
				*/
              onNodeUnselected: function (event, node) {
                  //console.log(node.text + ' was unselected');
              },
              onNodeAdd: function(nodeId) {
            	  var newNode = null;
            	  $.ajax({
      				url:'/fk/savekw',
      			    type:'GET', //GET
      			    async:false,    //或false,是否异步
      			    data:{
      			    	flowid:flowid,
      			    	keywordValue:'关键词',
      			    	parentid:nodeId
      			    },
      			    //timeout:5000,    //超时时间
      			    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text

      			    success:function(data,textStatus,jqXHR){
      			        //console.log(data)
      			        //successfully insert to database
      			  	    newNode = [
      			    	      {
      			    	        text: data.keywordValue,
      			    	        href: '#demo',
      			    	        nodes:[],
      			  	  	        item_id:data.id,
      			  	            item_parent:data.parentId,
      			    	        //tags: ['11']
      			    	      }
      			    	  ];      			          
      			    },
      			    error:function(xhr,textStatus){
      			        //console.log(xhr.responseText)
      			    },
      			    complete:function(){
      			    	//console.log('结束')
      			    }
      			});
            	return newNode;
            	  
              },
              onNodeRemove: function(rmList){
            	  //console.log(Array.isArray(rmList))
            	  //console.log(rmList)
            	  var del_status='';
            	  $.ajax({
  					url:'/fk/removekw',
  				    type:'POST', //GET
  				    async:false,    //或false,是否异步
  				    data:{
  				    	listParam:rmList
  				    },
  				    //timeout:5000,    //超时时间
  				    dataType:'text',    //返回的数据格式：json/xml/html/script/jsonp/text
  				    success:function(data,textStatus,jqXHR){
  				    	del_status = 'ok';
  				    },
  				    error:function(xhr,textStatus){
  				    },
  				});
            	//console.log(del_status)
            	return del_status;
              }
            });
          };
          
          var $selectableTree = initSelectableTree();

  		});
  	</script>
</body>
</html>